package main

import (
	"errors"
	"fmt"
	"iot-base/common/cache"
	"iot-base/common/dbconn"
	"iot-base/common/logger"
	"iot-base/common/notify"
	"time"

	"gorm.io/gorm"
)

func getData(uid, id string, thing *cache.ThingInfo) error {

	//logger.SLog.Info("-----------getdata----------",uid)
	devMsg, err := GetDevMsg(uid, conn)
	logger.SLog.Info("-----------getdata----------", uid, err)
	if err == nil && devMsg != nil && len(devMsg.Dev) > 0 {
		if devMsg.Dev[0].Conect == "Offline" {
			//fmt.Println("error------------------offline", uid)
			logger.SLog.Error("device is offline but in map is online", uid, id)

			// dbconn.DBConnection.Transaction(func(tx *gorm.DB) error {
			// 	var sb SB

			// 	sb.Sbzt = 1
			// 	sb.Gmzt = 1

			// 	err := tx.Where("id = ?", id).First(&sb).Error
			// 	sb.Id = id
			// 	sb.Sbbh = id
			// 	sb.Zhgxsj = time.Now()
			// 	if err == nil {
			// 		err = tx.Save(&sb).Error
			// 	} else {
			// 		err = tx.Create(&sb).Error
			// 	}
			// 	return err
			// })

			return errors.New("device is offline")
		}

		noSmoke := false
		noAutoSW := false
		noSpeaker := false
		noELocker := false
		now := time.Now().Unix()
		cuid := devMsg.Dev[0].UID
		if cuid != uid {
			//id = boxistrue[cuid]
			logger.SLog.Error("wrong protocol recved uid tuid id", uid, cuid, id)
			return errors.New("device recv error")
		}
		smap, err := getSysMask(cuid)
		if err != nil || smap == nil {
			logger.SLog.Error("wrong protocol getSysMask", uid, cuid, id, err, smap)
		} else {
			siolist := smap["IOShieldList"]
			if siolist != nil {
				iolist, _ := siolist.(*[]int)
				if iolist != nil {
					for _, io := range *iolist {
						if io == 0 {
							noSpeaker = true
							break
						}
					}

				}
			}

			slist, ok := smap["AlarmShieldList"]
			if ok && slist != nil {
				alist, okints := slist.(*[]int)
				if okints && alist != nil {
					/*
					   0,  重合闸
					   11, // 重合闸通信;
					   12, //电源板掉线
					   13, //电源板电压 欠压/过高
					   14, // 电源板 Outlet 电流 过高
					   15, //电源板 Outlet 继电器出错
					   16, //220V 过压/欠压;
					   17, // DC12V 过压/欠压;
					   18, //AC24V 过压/欠压;
					   19, //SMbus 出错
					   20, // 温度
					   21, // 湿度
					   22, // 机箱 ACC 倾斜
					   23, // 机箱震动;
					   24, // 摄像头掉线;
					   25, //风扇转速过低
					   26, // 水浸;
					   27, // 防雷设备失效
					   28, //烟雾发生
					   29, // =1 未授权 开箱门是否授权
					   30, //电子锁 未上锁
					   31, // 保留

					*/
					for _, shield := range *alist {
						switch shield {
						case 0, 11:
							noAutoSW = true
							devMsg.Dev[0].AutoSw.State = "disabled"
							devMsg.Dev[0].AutoSw.AC220.S = "disabled"
						case 20:
							devMsg.Dev[0].Envi.Tem.S = "disabled"
						case 21:
							devMsg.Dev[0].Envi.Hum.S = "disabled"
						case 22:
							devMsg.Dev[0].Envi.Acc.State = "disabled"
						case 23:
							devMsg.Dev[0].Envi.Shock.State = "disabled"
						case 25:
							devMsg.Dev[0].Envi.Fan.State = "disabled"
						case 26:
							devMsg.Dev[0].Envi.InWater = "disabled"
						case 27:
							devMsg.Dev[0].SPD.Status = "disabled"
						case 28:
							noSmoke = true
						case 30:
							noELocker = true

						}

					}
				} else {
					fmt.Println("getsysmask error--------to []int--")
				}
			}
		}

		dbconn.DBConnection.Transaction(func(tx *gorm.DB) error {

			var pSB = &SB{}
			//var sb SB
			err := tx.Where("id = ?", id).First(pSB).Error
			isSave := false
			pSB.Id = id
			ip := thing.Params["IP"]
			if pSB.Sbbh != ip {
				isSave = true
				pSB.Sbbh = ip

			}
			//pSB.Sbbh = thing.Params["IP"]
			pSB.Zhgxsj = time.Now()
			if pSB.Sbzx != 0 {
				pSB.Sbzx = 0
				isSave = true
			}
			if pSB.Gmzt != 0 {
				pSB.Gmzt = 0
				isSave = true
			}
			stationName := thing.GetStationName()
			if stationName != pSB.Sbdz {
				pSB.Sbdz = stationName
				isSave = true
			}
			if pSB.Kzsbmc != thing.Thing.SName {
				pSB.Kzsbmc = thing.Thing.SName
				isSave = true
			}

			//pSB.Kzsbmc = thing.Thing.SName
			//pSB.Sbdz = thing.GetStationName()
			pSB.By1 = pSB.Sbdz
			sid := thing.StationID
			sThing, _ := cache.GetThing(sid)
			if sThing != nil {

				if pSB.By2 == sThing.GetStationName() {
					pSB.By2 = sThing.GetStationName()
					isSave = true
				}
			}
			pSB.By3 = thing.Thing.Lon
			pSB.By4 = thing.Thing.Lat
			pSB.Sbzt = 0

			if devMsg.Dev[0].Envi.InWater == "true" {

				if pSB.Sbjs != 1 {
					isSave = true
					pSB.Sbjs = 1
					pSB.Sbzt = 1
				}
			}
			if devMsg.Dev[0].Envi.Door.Open == "true" {

				if pSB.Mzt != 1 {
					isSave = true
					pSB.Mzt = 1
					pSB.Sbzt = 1
				}
			}

			if isSave {
				pSB.Dy = devMsg.Dev[0].AutoSw.AC220.V
				if err != nil {
					err = tx.Create(pSB).Error
				} else {

					err = tx.Save(pSB).Error
				}
				return err
			}
			return nil

		})
		//dbconn.DBConnection.Save(&sb)

		notify.RawData(id, "SpeakerEnabled", "", 0, !noSpeaker, now, now)
		notify.RawData(id, "elockerEnabled", "", 0, !noELocker, now, now)
		notify.RawData(id, "SmokeEnabled", "", 0, !noSmoke, now, now)
		notify.RawData(id, "", "", 0, devMsg.Dev[0].Envi, now, now)
		notify.RawData(id, "CamDrop", "", 0, devMsg.Dev[0].CamDrop, now, now)
		notify.RawData(id, "SPD", "", 0, devMsg.Dev[0].SPD, now, now)
		notify.RawData(id, "AutoSw", "", 0, devMsg.Dev[0].AutoSw, now, now)

		notify.RawData(id, "AC220", "", 0, devMsg.Dev[0].AutoSw.AC220, now, now)
		//

		notify.RawData(id, "DC12", "", 0, devMsg.Dev[0].Pow.DC12, now, now)

		notify.RawData(id, "AC24", "", 0, devMsg.Dev[0].Pow.AC24, now, now)

		fmt.Println("*****************************", devMsg.Dev[0].Sys.IO)
		ioStatus := "["
		isfirst := true
		for _, io := range devMsg.Dev[0].Sys.IO {
			if noAutoSW && io == 16 {
				continue
			}
			if io == 29 && noSmoke {
				continue
			}
			if io == 18 && noSpeaker {
				continue
			}
			if devMsg.Dev[0].SPD.Status == "disabled" && io == 31 {
				continue
			}
			if noELocker && io == 27 {
				continue
			}
			ios := fmt.Sprintf("%d", io)
			if isfirst {
				ioStatus = ioStatus + ios
			} else {
				ioStatus = ioStatus + "," + ios
			}
			isfirst = false
		}
		ioStatus = ioStatus + "]"
		notify.RawData(id, "IO status", "", 0, ioStatus, now, now)
		//notify.RawData(id, "humity", "", 0, devMsg.Dev[0].Envi.Hum.V, now, now)
	}
	return nil
}
